package controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.FolderTreeNode;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import bean.Folder;
import service.FolderService;

@Controller
@RequestMapping("/folder")
public class FolderController {
	@Resource
	private FolderService folderService;
	
	@RequestMapping("/createFolder")
	public @ResponseBody String CreateFolder(HttpServletRequest request, HttpServletResponse response, String folderName,
			 int parentFolder, String folderDesc){
		Folder folder = new Folder();
		folder.setFolderName(folderName);
		folder.setBelongTo(parentFolder);
		folder.setFolderDesc(folderDesc);
		if(parentFolder == 0){
			folder.setFolderPath("D:/File/"+folderName);
		}
		else{
			Folder parent = folderService.FindById(parentFolder);
			folder.setFolderPath(parent.getFolderPath()+"/"+folderName);
		}
		
		if(folderService.CreateFolder(folder)){
			return "success";
		}
		else{
			return "false";
		}
	}
	
	@RequestMapping(value="/folderTree",produces = "text/html;charset=UTF-8")
	public @ResponseBody void FolderTree(HttpServletRequest request, HttpServletResponse response) throws IOException{
		FolderTreeNode tree = folderService.FolderTree();
		System.out.println("getting foldertree...");
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("data", tree);
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().print(JSONArray.fromObject(tree.getNodes()).toString());
	}
}
